//
//  QLKBaseViewController.m
//  CloudsOutpatient
//
//  Created by zzs on 15/6/15.
//  Copyright (c) 2015年 HC. All rights reserved.
//

#import "QLKBaseViewController.h"
#import "SDImageCache.h"
#import "AppDelegate.h"
@interface QLKBaseViewController ()<UITextFieldDelegate,UIGestureRecognizerDelegate>
{
    int     _lastPosition2;                     // 记录上次滑动的位置
    BOOL    _isDecelerate;                      // 是否减速
    BOOL    _isDrag;                            //是否滑动
    MBProgressHUD *hud;
}

@property (retain,nonatomic) UIView* emptyDataBackgroundView;
@property (retain,nonatomic) UIImageView* logo;
@property (retain,nonatomic) UILabel* titleLabel;
@property (retain,nonatomic) UILabel* desLabel;

@end

@implementation QLKBaseViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if ((self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
#ifdef __IPHONE_7_0
        if([UIViewController instancesRespondToSelector:@selector(edgesForExtendedLayout)]) {
            self.edgesForExtendedLayout = UIRectEdgeNone;
            //            self.edgesForExtendedLayout = UIRectEdgeAll;
        }
        
        if([UIViewController instancesRespondToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
            [self setNeedsStatusBarAppearanceUpdate];
        }
#endif
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   // self.navigationController.interactivePopGestureRecognizer.delegate = self;
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIColor createImageWithColor:[UIColor colorWithHexString:@"00b1ef"]] forBarMetrics:UIBarMetricsDefault];
    //    [self setNaviTitle:@"aa"];
    //    [self setNaviLeftButton];
    //    [self setNaviRightButton:@"分享赚钱"];
    //    [self setNaviMiddleButton:@"订单管理"];
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}

+ (id)getController:(NSString *)className withData:(id)data
{
    Class clazz = nil;
    QLKBaseViewController *controller = nil;
    
    if(className && (clazz = NSClassFromString(className))) {
        controller = [[NSClassFromString(className) alloc] init];
    } else {
        controller = [[QLKBaseViewController alloc] init];
    }
    controller.data = data;
    
    return controller;
}

- (void)showEmptyDataBackgroundViewWithTitle:(NSString*)title  description:(NSString*)description
{
    [self showEmptyDataBackgroundViewWithImage:[UIImage imageNamed:@""] title:title description:description];
}
/**
//显示空数据背景
- (void)showEmptyDataBackgroundViewWithImage:(UIImage *)logo title:(NSString*)title  description:(NSString*)description
{
    if (!self.emptyDataBackgroundView) {
        _emptyDataBackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kMainScreenFrameWitdh, 267)];
        _emptyDataBackgroundView.backgroundColor = Colorf7f7f7;
        [self.view addSubview:_emptyDataBackgroundView];
        [_emptyDataBackgroundView addSubview:_logo];
        __weak __typeof(&*self)weakSelf = self;
        [_emptyDataBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.view).width.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        
        _logo = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 122, 129)];
        
        [_emptyDataBackgroundView addSubview:_logo];
        [_logo mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(weakSelf.emptyDataBackgroundView);
            make.top.equalTo(weakSelf.view).with.offset(31);
        }];
        
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kMainScreenFrameWitdh, 16)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = Color707070;
        _titleLabel.font = [UIFont systemFontOfSize:16];
        
        [_emptyDataBackgroundView addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(weakSelf.emptyDataBackgroundView);
            make.top.equalTo(weakSelf.logo.mas_bottom).with.offset(15);
        }];
        
        _desLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kMainScreenFrameWitdh, 12)];
        _desLabel.textAlignment = NSTextAlignmentCenter;
        _desLabel.textColor = Color707070;
        _desLabel.font = [UIFont systemFontOfSize:14];
        
        [_emptyDataBackgroundView addSubview:_desLabel];
        [_desLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(weakSelf.emptyDataBackgroundView);
            make.top.equalTo(weakSelf.titleLabel.mas_bottom).with.offset(5);
        }];
    }
    self.emptyDataBackgroundView.hidden = NO;
    [self.logo setImage:logo];
    self.titleLabel.text = title;
    self.desLabel.text = description;
}
**/
- (void)hideShowEmptyDataBackgroundView
{
    self.emptyDataBackgroundView.hidden = YES;
}

- (void)setNaviMiddleButton: (NSString* )title {
    CGSize textSize = [title sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:18], NSFontAttributeName, nil]];
    UIView* backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, textSize.width + 12, 44)];
    
    // 按钮
    UIButton* middleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    middleButton.frame = CGRectMake(0, 0, textSize.width, 44);
    [middleButton setTitle:title forState:UIControlStateNormal];
    [middleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    middleButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:18];
    [middleButton addTarget:self action:@selector(clickMiddleButton:) forControlEvents:UIControlEventTouchUpInside];
    [backgroundView addSubview:middleButton];
    
    // 图标
    UIImageView* arrowImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navi_img_arrow_down"]];
    arrowImage.frame = CGRectMake(textSize.width + 3, 0, 9, 5);
    arrowImage.center = CGPointMake(arrowImage.center.x, backgroundView.center.y);
    [backgroundView addSubview:arrowImage];
    
    self.navigationItem.titleView = backgroundView;
}

- (void)clickMiddleButton:(id)sender
{
    
}

- (void)setNaviTitle:(NSString* )title {
    self.title = title;
    
    NSShadow *shadowAttribute = [[NSShadow alloc]init];
    shadowAttribute.shadowColor = [UIColor clearColor];
    shadowAttribute.shadowOffset = CGSizeMake(0, -1);
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor whiteColor], NSForegroundColorAttributeName,
                                                                     shadowAttribute, NSShadowAttributeName,
                                                                     [UIFont fontWithName:@"Arial" size:18], NSFontAttributeName,
                                                                     nil]];
}

- (void)setNaviLeftButton {
    [self setNaviLeftButton:@"返回"];
}
- (void)setTabbarHidden:(BOOL)hidden{
    [SharedAppDelegate.tabBarController setTabBarHidden:hidden];
}
- (void)setNaviLeftButton:(NSString* )title
{
    UIImage * lpImage = [UIImage imageNamed:@"navi_btn_backarrow_def.png"];
    UIImage * lpImage2 = [UIImage imageByApplyingAlpha:0.5 image:lpImage];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
    [btn setImage:lpImage forState:UIControlStateNormal];
    [btn setImage:lpImage2 forState:UIControlStateHighlighted];
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, -80, 0, 0);
    [btn addTarget:self action:@selector(clickLeftButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = backBtn;
}

- (void)setRightButtonAtMinRect:(NSString*)title
{
    
    if (IS_NOT_EMPTY(title)) {
        CGSize textSize = [title sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16.0f], NSFontAttributeName, nil]];
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton.frame = CGRectMake(0, 0, textSize.width+20, textSize.height);
        [rightButton setTitle:title forState:UIControlStateNormal];
        [rightButton setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -30)];
        rightButton.titleLabel.font=[UIFont systemFontOfSize:15];
        UIView *backBtnView = [[UIView alloc] initWithFrame:rightButton.bounds];
        [rightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
        [backBtnView addSubview:rightButton];
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtnView];
        [self.navigationItem setRightBarButtonItem:rightButtonItem animated:YES];
    }else{
        self.navigationItem.rightBarButtonItem=nil;
    }
}

- (void)setNaviRightButton:(NSString* )title
{
    if (IS_NOT_EMPTY(title)) {
        CGSize textSize = [title sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16.0f], NSFontAttributeName, nil]];
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
      
        rightButton.frame = CGRectMake(0, 0, textSize.width+20, textSize.height);
        [rightButton setTitle:title forState:UIControlStateNormal];
        [rightButton setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -30)];
        rightButton.titleLabel.font=[UIFont systemFontOfSize:15];
        [rightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        [self.navigationItem setRightBarButtonItem:rightButtonItem animated:YES];
    }else{
        self.navigationItem.rightBarButtonItem=nil;
    }
}
- (void)setNaviRightImgButton:(NSString* )imgName
{
    if (IS_NOT_EMPTY(imgName)) {
        UIImage *img1 = [UIImage imageNamed:imgName];
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton.frame = CGRectMake(0, 10, 20, 20);
        [rightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
        [rightButton setImage:img1 forState:UIControlStateNormal];
         UIImage * lpImage2 = [UIImage imageByApplyingAlpha:0.5 image:img1];
        [rightButton setImage:lpImage2 forState:UIControlStateHighlighted];
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        [self.navigationItem setRightBarButtonItem:rightButtonItem animated:YES];
    }
}
- (void)setNaviRightImgButton:(NSString* )imgName frame:(CGRect)frame
{
    if (IS_NOT_EMPTY(imgName)) {
        UIImage *img1 = [UIImage imageNamed:imgName];
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton.frame = frame;
        [rightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
        [rightButton setImage:img1 forState:UIControlStateNormal];
        UIImage * lpImage2 = [UIImage imageByApplyingAlpha:0.5 image:img1];
        [rightButton setImage:lpImage2 forState:UIControlStateHighlighted];
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        [self.navigationItem setRightBarButtonItem:rightButtonItem animated:YES];
    }
}
- (void)clickRightButton:(id)sender {
    
}

-(void)clickLeftButton:(UIButton*)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setTitle:(NSString *)title
{
    [super setTitle:title];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[SDImageCache sharedImageCache] setSuspended:NO];
}

- (void)handlePanelHighlight:(id)sender{
    [[(UIView*)sender subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[UIButton class]]) {
            [obj setHighlighted:[(UIButton*)sender isHighlighted]];
        }
    }];
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

#ifdef __IPHONE_7_0
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (BOOL)prefersStatusBarHidden
{
    return NO;
}
#endif

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return UIInterfaceOrientationIsPortrait(toInterfaceOrientation);
}

- (BOOL)shouldAutorotate
{
    return YES;
}

#pragma mark
#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    _isDecelerate = YES;
    
    if (!decelerate) {
        [[SDImageCache sharedImageCache] setSuspended:NO];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int currentPostion = scrollView.contentOffset.y;
    
    if (_isDrag) {
        if ((abs(_lastPosition2 - currentPostion) < 3 && _isDecelerate) || abs(_lastPosition2 - currentPostion) < 2) { // 快速滑动减速时或者手指慢速移动时, 恢复图片下载线程
            [[SDImageCache sharedImageCache] setSuspended:NO];
            _isDrag = NO;
        }else {
            [[SDImageCache sharedImageCache] setSuspended:YES];
        }
    }else{
        [[SDImageCache sharedImageCache] setSuspended:NO];
    }
    
    _lastPosition2 = currentPostion;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _isDecelerate = NO;
    _isDrag = YES;
    
    [[SDImageCache sharedImageCache] setSuspended:NO];
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [[SDImageCache sharedImageCache] setSuspended:NO];
    _isDrag = NO;
}


-(void)showLoadingView{
    hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
-(void)hideLoadingView{
    [hud hide:YES];
}


- (void)performShowMessage:(NSString *)mes {
    hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = mes;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:2];
}

- (void)showCustomBackgroundMessage:(NSString *)msg
{
   // [ATMHud showMessage:msg];
}
-(void)searchMedicationWithKeyword:(NSString*)keyword{
    
}
@end
